package com.zhilei;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Path2D;

public class BouncingHeart extends JPanel {
    private final Timer timer;
    private double scale = 1.0; // 控制心形的缩放
    private boolean growing = true; // 标记心形是否在增大

    public BouncingHeart() {
        // 设置定时器，每16毫秒更新一次
        timer = new Timer(16, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 每次更新时改变缩放比例
                if (growing) {
                    scale += 0.02;
                    if (scale > 1.5) {
                        growing = false;
                    }
                } else {
                    scale -= 0.02;
                    if (scale < 1.0) {
                        growing = true;
                    }
                }
                repaint(); // 重绘面板
            }
        });
        timer.start(); // 启动定时器
    }

    public static void main(String[] args) {
        JFrame frame = new JFrame("跳动的心");
        BouncingHeart panel = new BouncingHeart();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.add(panel);
        frame.setVisible(true);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);

        // 计算心形的位置和大小
        Graphics2D g2d = (Graphics2D) g;
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        int width = getWidth();
        int height = getHeight();

        // 设置画笔颜色
        g2d.setColor(Color.RED);

        // 绘制跳动的心形
        int size = (int) (100 * scale); // 根据缩放比例调整心形的大小
        int x = (width - size) / 2;
        int y = (height - size) / 2;

        g2d.fill(new HeartShape(x, y, size));
    }

    // 定义一个自定义的心形路径类
    static class HeartShape extends Path2D.Double {
        public HeartShape(int x, int y, int size) {
            super();
            // 心形的路径公式
            moveTo(x + size / 2, y + size / 4);
            curveTo(x + size / 4, y, x, y + size / 3, x + size / 2, y + size);
            curveTo(x + size, y + size / 3, x + 3 * size / 4, y, x + size / 2, y + size / 4);
            closePath();
        }
    }
}
